<?php
    define('DATABASE','dealscombined');
require("/var/www/sandbox/dealscombined.co.uk/scripts/connect.php");

// Select DB
$db=mysql_select_db(DATABASE,$connect);
if(!$db) {
die('Can\'t use DATABASE : '.mysql_error());
}

$mappings = array();
$mappings = getMappings();

$result = mysql_query("SELECT * FROM unmapped_products");

while($row = mysql_fetch_assoc($result)){
	
	foreach($mappings as $mapping){
		
		//$match = findMatches($row['title'], $mapping);
		
		$count = "0";
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $row['title'])){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['second_word'])."/i", $row['title'])){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['third_word'])."/i", $row['title'])){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['fourth_word'])."/i", $row['title'])){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['fifth_word'])."/i", $row['title'])){
			
		$count++;
	}
		
		if($count >= 3){
		mysql_query ("UPDATE products SET mapped_category = '".$mapping['category_ids']."' WHERE id =".$row['product_id']);
		break;
	}
	
		
		
	}
	
}

function getMappings(){
	$mappings = array();
	
	$result = mysql_query("SELECT * FROM mappings m INNER JOIN mapping_targets t ON m.id = t.ruleset_id");
	
	while($row = mysql_fetch_assoc($result)){
		
		$mappings[] = $row;
	}
	
	return $mappings;
	
}

function findMatches($product, $mapping){
	
	$count = "0";
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $product['title']) === TRUE){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $product['title']) === TRUE){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $product['title']) === TRUE){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $product['title']) === TRUE){
			
		$count++;
	}
	
	if(preg_match("/".preg_quote($mapping['first_word'])."/i", $product['title']) === TRUE){
			
		$count++;
	}
	
	echo $count;
	
	if($count >= 3){
		echo "UPDATE products SET mapped_category = '".$mapping['category_ids']."' WHERE id =".$product['product_id'];
		return TRUE;
	}
	
	return FALSE;
}
?>